/**
 * 团队管理 Composable
 */
import { ref, computed } from 'vue'

export function useTeamManagement() {
  // 响应式数据
  const teamInfo = ref(null)
  const isTeamLeader = ref(false)
  const teamMode = ref(false)
  const showTeamInvitationModal = ref(false)
  const teamLoading = ref(false)
  const teamError = ref('')

  // 计算属性
  const showTeamSection = computed(() => {
    // 这个计算属性需要从外部传入taskData，或者改为通过参数传入
    return teamMode.value // 暂时只检查teamMode
  })

  // 方法
  const checkExistingTeam = async (taskId) => {
    if (!taskId) return

    teamLoading.value = true
    teamError.value = ''

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const currentUser = uni.getStorageSync('userInfo')
      let userId = null
      if (currentUser && currentUser.uid) {
        userId = currentUser.uid
      } else {
        try {
          const tokenPayload = JSON.parse(atob(token.split('.')[1]))
          userId = tokenPayload.uid || tokenPayload.sub
        } catch (tokenError) {
          console.error('解析token失败:', tokenError)
          throw new Error('用户信息获取失败')
        }
      }

      if (!userId) {
        throw new Error('用户信息获取失败')
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/team/check-existing`,
        method: 'POST',
        data: {
          taskId: Number(taskId),
          userId: Number(userId)
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        if (response.data.hasTeam) {
          teamInfo.value = response.data.teamInfo
          isTeamLeader.value = response.data.isLeader
          teamMode.value = true
        } else {
          teamInfo.value = null
          isTeamLeader.value = false
          teamMode.value = false
        }
      }
    } catch (err) {
      teamError.value = err.message || '检查团队状态失败'
      console.error('检查团队状态失败:', err)
    } finally {
      teamLoading.value = false
    }
  }

  const createTeam = async (taskId, teamName = '临时团队') => {
    if (!taskId) return

    try {
      const token = uni.getStorageSync('accessToken')
      const currentUser = uni.getStorageSync('userInfo')
      
      if (!token) {
        throw new Error('请先登录')
      }

      let leaderId = null
      if (currentUser && currentUser.uid) {
        leaderId = currentUser.uid
      } else {
        try {
          const tokenPayload = JSON.parse(atob(token.split('.')[1]))
          leaderId = tokenPayload.uid || tokenPayload.sub
        } catch (tokenError) {
          console.error('解析token失败:', tokenError)
          throw new Error('用户信息获取失败')
        }
      }

      if (!leaderId) {
        throw new Error('用户信息获取失败')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team/create-invitation',
        method: 'POST',
        data: {
          taskId: Number(taskId),
          leaderId: Number(leaderId),
          teamName: teamName,
          inviteeIds: []
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        if (response.data.teamInfo) {
          teamInfo.value = response.data.teamInfo
          isTeamLeader.value = true
          teamMode.value = true
        }
        return response.data
      } else {
        throw new Error(response.data?.message || '创建团队失败')
      }
    } catch (err) {
      console.error('创建团队失败:', err)
      throw err
    }
  }

  const leaveTeam = async (teamId) => {
    if (!teamId) return

    try {
      const token = uni.getStorageSync('accessToken')
      const currentUser = uni.getStorageSync('userInfo')
      
      let userId = null
      if (currentUser && currentUser.uid) {
        userId = currentUser.uid
      } else {
        try {
          const tokenPayload = JSON.parse(atob(token.split('.')[1]))
          userId = tokenPayload.uid || tokenPayload.sub
        } catch (tokenError) {
          console.error('解析token失败:', tokenError)
          throw new Error('用户信息获取失败')
        }
      }

      if (!userId) {
        throw new Error('用户信息获取失败')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team/leave-team',
        method: 'POST',
        data: {
          teamId: teamId,
          userId: userId
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        // 退出团队后重置状态
        teamInfo.value = null
        isTeamLeader.value = false
        teamMode.value = false
        return true
      } else {
        throw new Error(response.data?.message || '退出团队失败')
      }
    } catch (err) {
      console.error('退出团队失败:', err)
      throw err
    }
  }

  const dissolveTeam = async (teamId) => {
    if (!teamId) return

    try {
      const token = uni.getStorageSync('accessToken')
      const currentUser = uni.getStorageSync('userInfo')
      
      let leaderId = null
      if (currentUser && currentUser.uid) {
        leaderId = currentUser.uid
      } else {
        try {
          const tokenPayload = JSON.parse(atob(token.split('.')[1]))
          leaderId = tokenPayload.uid || tokenPayload.sub
        } catch (tokenError) {
          console.error('解析token失败:', tokenError)
          throw new Error('用户信息获取失败')
        }
      }

      if (!leaderId) {
        throw new Error('用户信息获取失败')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team/dissolve-team',
        method: 'POST',
        data: {
          teamId: teamId,
          leaderId: leaderId
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        // 解散团队后重置状态
        teamInfo.value = null
        isTeamLeader.value = false
        teamMode.value = false
        return true
      } else {
        throw new Error(response.data?.message || '解散团队失败')
      }
    } catch (err) {
      console.error('解散团队失败:', err)
      throw err
    }
  }

  const openInvitationModal = () => {
    showTeamInvitationModal.value = true
  }

  const closeInvitationModal = () => {
    showTeamInvitationModal.value = false
  }

  return {
    // 响应式数据
    teamInfo,
    isTeamLeader,
    teamMode,
    showTeamInvitationModal,
    teamLoading,
    teamError,
    
    // 计算属性
    showTeamSection,
    
    // 方法
    checkExistingTeam,
    createTeam,
    leaveTeam,
    dissolveTeam,
    openInvitationModal,
    closeInvitationModal
  }
}
